<script setup lang="ts">
import pageFooter from "@/components/pageFooter/index.vue";
import { useTheme } from "@/composables/useTheme";
import { onShow, onLoad, onHide, onUnload } from "@dcloudio/uni-app";
import Cache from "@/utils/cache";
import { USER_INFO, LOGIN_STATUS } from "@/config/cache";
import { JumpPath, Tips } from "@/utils";
import {
  marketGet,
  getPolicyList,
  getReminderList,
  getSave,
  remove,
} from "@/api/home";
import { getOpenidByCode, getCurlOauth, getWechatFollow } from "@/api/user";
const { colorStyle } = useTheme();
let userInfo = reactive({});
let isShowAllMenu = ref(false);
let shareData = ref({
  business_id: "",
  urltype: "",
});
onHide(() => {
  closeFollowCode();
});
onUnload(() => {
  closeFollowCode();
});
onLoad((option) => {
  // 分享进来的存储，底部菜单区分
  if (option.business_id) {
    shareData.value.business_id = option.business_id;
    shareData.value.urltype = option.urltype;
    Cache.set("urltype", option.urltype);
    Cache.set("business_id", option.business_id);
    isShowAllMenu.value = false;
  }
});
onShow(() => {
  if (Cache.get("business_id")) {
    isShowAllMenu.value = false;
  } else {
    isShowAllMenu.value = true;
  }
  if (Cache.get(USER_INFO)) {
    userInfo = JSON.parse(Cache.get(USER_INFO));
  }
  getWechatFollowHanlder();
});
let remindList = ref([]);
// 我的提醒列表
async function getRemindListListHanlder() {
  remindList.value = [];
  let { data } = await getReminderList({
    business_id: shareData.value.business_id || userInfo.id,
  });
  remindList.value = data.list;
}
// 添加提醒
async function remindSaveHandler(id) {
  const params = {
    business_id: shareData.value.business_id || userInfo.id, //企业资料的企业ID
    date_json: JSON.stringify(remindList.value),
  };

  let { data, info } = await getSave(params);
  Tips({
    title: info,
  });
  getRemindListListHanlder(userInfo.id);
  close3();
}
// 到价提醒
async function addTipHandler() {
  remindList.value.push({
    title: "",
    is_type: "",
    price: "",
  });
}
function tipSaveHandler() {
  if (!remindList.value.length) return Tips({ title: "请添加提醒" });
  const emptyItem = remindList.value.find(
    (item) => !item.policy_id || !item.is_type || !item.price
  );
  if (emptyItem) {
    Tips({ title: "请完善信息" });
    return;
  }
  remindSaveHandler();
}
function delTipHandler(index) {
  if (remindList.value[index].id) {
    // 从数据中删除
    uni.showModal({
      content: "是否确认删除",
      success: (res) => {
        if (res.confirm) {
          removeTipHandler(remindList.value[index].id);
        }
      },
    });
  } else {
    //删除自定义添加的订阅项
    remindList.value.splice(index, 1);
  }
}
async function removeTipHandler(id) {
  const params = { id, business_id: userInfo.id };
  const { info } = await remove(params);
  Tips({
    title: info,
  });
  getRemindListListHanlder();
}

let subscribe = ref(false);
let wechat_qrcode = ref("");
// 判断是否关注公众号
async function getWechatFollowHanlder() {
  let { data, code } = await getWechatFollow();
  subscribe.value = !!data.subscribe;
  wechat_qrcode.value = data.wechat_qrcode;
  if (code == 1) {
    getRemindListListHanlder();
    getPolicyListHanlder(); //获取品类列表
  }
}
let openFollowCode = ref(false);
function openFollowCodeHandler() {
  openFollowCode.value = true;
}
function closeFollowCode() {
  openFollowCode.value = false;
}

// 订阅---start---
const onSubscribeSuccess = (e) => {
  let subscribeDetails = JSON.parse(e.detail.subscribeDetails); // 全部的模板
  for (let i in subscribeDetails) {
    let subKey = subscribeDetails[i]; // 获取每个模板的状态
    let status = JSON.parse(subKey);
    console.log("success:状态：", status.status);
    switch (status.status) {
      case "reject":
        Tips({ title: `用户拒绝订阅消息` });
        break;
      case "cancel":
        Tips({ title: `用户取消订阅消息` });
        break;
      case "filter":
        Tips(`第${i}条消息应该标题同名被后台过滤`);
        break;
      default:
        addTipHandler();
        // 允许
        break;
    }
  }
};

const onSubscribeError = (err) => {
  uni.showModal({
    title: err,
  });
  console.log("出现错误");
};
// ----订阅end------------
let remindCurrent = ref(0); //选择的第几个订阅索引
const picker1 = ref(false);
function openPik1(index) {
  if (!policyList.value.length) return Tips({ title: "暂无商品列表" });
  remindCurrent.value = index;
  picker1.value = true;
}
function closePik1() {
  picker1.value = false;
}
// 品类确认
function pik1Confirm(e) {
  const data = e.value[0];
  remindList.value[remindCurrent.value].policy_id = data.id;
  remindList.value[remindCurrent.value].title = data.title;
  closePik1();
}

const picker2 = ref(false);
const columns = ref([
  [
    { id: 1, title: "销售" },
    { id: 2, title: "回购" },
  ],
]);
function openPik2(index) {
  remindCurrent.value = index;
  picker2.value = true;
}
function closePik2() {
  picker2.value = false;
}
// 品类确认
function pik2Confirm(e) {
  const data = e.value[0];
  remindList.value[remindCurrent.value].is_type = data.id;
  closePik2();
}
let policyList = ref([]);
async function getPolicyListHanlder() {
  policyList.value = [];
  let { data } = await getPolicyList({
    business_id: shareData.value.business_id || userInfo.id,
  });
  policyList.value = [data.list];
}
</script>
<template>
  <view class="wrap" :style="colorStyle">
    <view class="pop_box pop_box3" v-if="remindList.length">
      <!-- <view class="pop_title">到价提醒</view> -->
      <view class="pop_body">
        <view class="set_item flex_sb set_item1">
          <view class="input_item">商品</view>
          <view class="input_item">方向</view>
          <view class="input_item">价格</view>
        </view>
        <view
          class="set_item flex_sb"
          v-for="(item, index) in remindList"
          :key="index"
        >
          <view
            class="input_item"
            :class="{ black: item.title }"
            @click="openPik1(index)"
          >
            {{ item.title || "请选择" }}
          </view>
          <view
            class="input_item"
            :class="{ black: item.is_type == 1 || item.is_type == 2 }"
            @click="openPik2(index)"
          >
            <text v-if="item.is_type == 1"> 销售 </text>
            <text v-else-if="item.is_type == 2"> 回购 </text>
            <text v-else> 请选择 </text>
          </view>
          <view class="input_item">
            <input
              type="digit"
              placeholder="请输入价格"
              placeholder-class="input_placeholder"
              v-model="item.price"
            />
          </view>
          <view
            class="iconfont icon-guanbi1"
            @click="delTipHandler(index)"
          ></view>
        </view>
      </view>
    </view>
    <view class="empty_box" v-else>
      <up-empty icon="/static/image/empty.png"> </up-empty>
    </view>
    <view class="pop_footer btn_box flex_sb">
      <view class="pop_btn_item btn_item1" v-if="subscribe">
        <wx-open-subscribe
          template="9SYqoZRxl_Z1Qw74WzNPux05CB6TvLdqXk05hWKUHZQ"
          id="subscribe-btn"
          @error="onSubscribeError"
          @success="onSubscribeSuccess"
          style="width: 100%"
        >
          <component :is="'script'" type="text/wxtag-template">
            <component :is="'style'">
              .btn{ width: 100%;padding:10px 0;display: flex;
              justify-content:center;align-content: center} .subscribe-btn{
              width: 100%;color: #000;font-weight:700;font-size:14px;
              text-align: center;}
            </component>
          </component>
          <component :is="'script'" type="text/wxtag-template">
            <div class="btn">
              <button class="subscribe-btn">新增提醒</button>
            </div>
          </component>
        </wx-open-subscribe>
      </view>
      <view class="pop_btn_item" @click="openFollowCodeHandler" v-else>
        新增提醒
      </view>
      <view class="pop_btn_item btn_item2" @click="tipSaveHandler">
        保存设置
      </view>
    </view>
    <!-- 关注弹窗start------- -->
    <view class="followCode" v-if="openFollowCode">
      <view class="pictrue">
        <view class="img_box">
          <image :src="wechat_qrcode" mode="aspectFill" />
        </view>

        <view class="follow_text"> 长按图片即可关注 </view>
      </view>
      <view class="mask" @click="closeFollowCode"></view>
    </view>
    <!-- 关注弹窗end------- -->
    <view class="uni-p-b-98"></view>
    <pageFooter
      :shareData="shareData"
      :isShowAllMenu="isShowAllMenu"
      :selected="6"
    ></pageFooter>

    <!-- 品类列表弹窗 -->
    <up-picker
      :show="picker1"
      :columns="policyList"
      keyName="title"
      @cancel="closePik1"
      @confirm="pik1Confirm"
    ></up-picker>
    <!-- 选择方向列表弹窗 -->
    <up-picker
      :show="picker2"
      :columns="columns"
      keyName="title"
      @cancel="closePik2"
      @confirm="pik2Confirm"
    ></up-picker>
  </view>
</template>

<style scoped lang="scss">
.wrap {
  min-height: 100vh;
  background: #fff;
  .pop_footer {
    // position: fixed;
    // left: 0;
    // bottom: 130rpx;
    // width: 100%;
    overflow: hidden;
    background: #fff;
    margin-top: 200rpx;
    .pop_btn_item {
      font-weight: bold;
      margin: 0 auto;
      border-radius: 20rpx;
      text-align: center;
      overflow: hidden;
      width: 45%;
      padding: 10px 0;
      font-size: 13px;
      color: var(--view-fontColor);
      border: 2px solid var(--view-theme);
    }
    .btn_item1 {
      padding: 0;
    }
    .btn_item2 {
      background: var(--view-theme);
      color: var(--view-fontColor);

      box-shadow: 0px 4px 20px 0px rgba(221, 203, 157, 0.4);
    }
  }
  .pop_box {
    border-radius: 20rpx 20rpx 0 0;
    overflow: hidden;
    .pop_title {
      height: 80rpx;
      line-height: 80rpx;
      color: #2e2e2e;
      font-size: 34rpx;
      font-weight: 700;
      text-align: center;
      border: 2rpx solid #f5f7f7;
      border-bottom: 2rpx solid #f5f7f7;
    }

    .pop_body {
      padding: 30rpx 20rpx;
      .set_item {
        position: relative;
        border-radius: 11rpx;
        background: rgba(244, 246, 247, 1);
        padding: 30rpx 60rpx;
        margin-bottom: 20rpx;
        .iconfont {
          position: absolute;
          left: -10rpx;
          top: -10rpx;
          font-size: 40rpx;
        }
        .black {
          color: rgba(46, 44, 44, 1) !important;
        }
        .input_item {
          text-align: center;
          position: relative;
          width: 33.33%;
          color: rgba(125, 136, 140, 1);

          font-size: 28rpx;
          &:not(:first-child)::before {
            position: absolute;
            content: "";
            top: 50%;
            transform: translateY(-50%);
            left: 0;
            width: 2rpx;
            height: 110%;
            border-radius: 11rpx;
            background: rgba(219, 217, 217, 1);
          }
          .input_placeholder {
            color: rgba(125, 136, 140, 1);
          }
          input {
            text-align: center;
            color: rgba(46, 44, 44, 1);
            font-size: 28rpx;
          }
        }
      }
      .set_item1 {
        padding: 0 60rpx;
        font-weight: bold;
        background: unset;
        .input_item {
          &::before {
            display: none;
          }
        }
      }
    }
  }
}
.followCode {
  .mask {
    z-index: 10000;
  }

  .pictrue {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 500rpx;
    // height: 720rpx;
    padding: 0 0 80rpx;
    border-radius: 12px;
    left: 50%;
    top: 50%;
    margin-left: -250rpx;
    margin-top: -360rpx;
    background: #fff;
    position: fixed;
    z-index: 10001;
    background-size: cover;
    background-repeat: no-repeat;

    .img_box {
      margin-top: 88rpx;
      width: 300rpx;
      height: 300rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .follow_text {
      color: #999;
      font-size: 30rpx;
      margin-top: 30rpx;
      text-align: center;
    }
  }
}
</style>
